/**
 * Created by evan on 2016/06/01.
 */
var gprop = require('./../etc/config').prop;
if(typeof __line=="undefined" && gprop.codeline){
    require('magic-globals');
}else{
    __line="";
}
var filename= __filename.split(gprop.file_split).pop();
var flog = require('./../controllers/log');
const fs=require("fs");
const download_path=gprop.server_path+"temp/download.txt";
function getClientIp(req){
	return req.headers['x-forwarded-for'] ||
		req.connection.remoteAddress ||
		req.socket.remoteAddress ||
		req.connection.socket.remoteAddress;
}
function writeDownloadLog(content) {
	if(!fs.existsSync(download_path)){
		fs.writeFileSync(download_path, content);
	}else{
		fs.appendFileSync(download_path, "\r\n"+content);
	}
}
module.exports = function (app) {
    app.all("/provision/version/:product_id/:version",function (req,res,next) {
	    var product_id=req.params.product_id;
	    var version=req.params.version;
	    if(!product_id || isNaN(product_id)){
	    	flog.do_log("error","error",filename,__line,"product id invalid");
	    	return res.json({success:false,reason:"product id invalid"});
	    }
	    if(!version){
		    flog.do_log("error","error",filename,__line,"version invalid");
		    return res.json({success:false,reason:"version invalid"});
	    }
	    var file_path=gprop.server_path+"temp"+req.path;
			if(!fs.existsSync(file_path)){
				flog.do_log("error","error",filename,__line,"version not found "+file_path);
				return res.json({success:false,reason:"version not found"});
			}
	    var stat=fs.statSync(file_path);
	    var content=new Date().Format("yyyy-MM-dd hh:mm:ss")+" "+getClientIp(req)+" "+req.method+" "+req.url+" "+stat.size+" Bytes";
	    res.writeHead(200);
			var time=new Date().getTime();
	    fs.createReadStream(file_path).pipe(res);
	    res.on('finish', function(){
		    var now=new Date().getTime();
		    var diff=now-time;
		    content+=" "+diff+" ms";
		    writeDownloadLog(content);
	    });
    });
		app.all("/download.txt",function (req,res,next) {
			res.writeHead(200);
			fs.createReadStream(download_path).pipe(res);
		})
    app.all("*",function (req,res,next) {
	    res.writeHead(404);
	    res.end();
    })
}